import axios from 'axios'
import { ElMessage } from 'element-plus'
import { getEnumByCode, ErrorTypes } from '@/enums/RetInfoEnum.ts'
//创建axios实例
const request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 20000,
})

//请求拦截器
request.interceptors.request.use((config) => {
  return config
})

//响应拦截器
request.interceptors.response.use(
  (response) => {
    const { code, msg } = response.data
    if (code !== 'M000') {
      ElMessage({
        type: 'error',
        message: msg,
      })
      return Promise.reject(new Error(msg))
    }
    return Promise.resolve(response.data)
  },
  (error) => {
    //处理网络错误
    const errorInfo = getEnumByCode(error.response.status)
    const msg = errorInfo ? ErrorTypes[errorInfo].message : error.message
    console.log(error)
    ElMessage({
      type: 'error',
      message: msg,
    })
    return Promise.reject(error)
  },
)
export default request
